#include "stm32f10x.h"
#include "wdtx_key.h"

struct keyStruct
{
	GPIO_TypeDef* GPIOx;
	uint16_t GPIO_Pin;
};

List KEY_NewInstance(uint16_t maxLength)
{
	return List_newInstance(sizeof(struct keyStruct),maxLength);
}

void KEY_destroy(List list)
{
	List_destroy(list);
}

void KEY_add(List group,GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin)
{
	GPIO_InitTypeDef GPIO_InitStructure;
	struct keyStruct key;
	
	RCC_APB2ENR_GPIO_Init(GPIOx);
	
	GPIO_InitStructure.GPIO_Pin = GPIO_Pin;
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
	GPIO_Init(GPIOx,&GPIO_InitStructure);
	
	GPIOx->BSRR |= GPIO_Pin;
	
	key.GPIOx = GPIOx;
	key.GPIO_Pin = GPIO_Pin;
	List_add(group,&key);
}

void KEY_addCustom(List group,GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin)
{
	struct keyStruct key;
	
	RCC_APB2ENR_GPIO_Init(GPIOx);
	
	GPIOx->BSRR |= GPIO_Pin;
	
	key.GPIOx = GPIOx;
	key.GPIO_Pin = GPIO_Pin;
	List_add(group,&key);
}
/**
*-->每次只允许按下一个按键
* @每10ms调用一次
* @parms: group(一个List封装的)按键组合
* @return: 被按下的按键在group中的索引+1，若无按键按下，返回NULL
*/
uint8_t KEY_scan(List group)
{
	uint8_t i;
	uint16_t length = List_getLength(group);
	struct keyStruct *key;
	for(i=0;i<length;i++)
	{
		key = List_get(group,i);
		if((key->GPIOx->IDR & key->GPIO_Pin) == 0)
		{
			return i+1;
		}
	}
	return NULL;
}
/**
*-->可同时按下多个按键
* @每10ms调用一次
* @parms: group(一个List封装的)按键组合
* @return: 一个uint8_t的参数，每一位为1代表该位索引上的按键按下
*/
uint8_t KEY_scanTogether(List group)
{
	uint8_t i,result =0;
	uint16_t length = List_getLength(group);
	struct keyStruct *key;
	for(i=0;i<length;i++)
	{
		key = List_get(group,i);
		if((key->GPIOx->IDR & key->GPIO_Pin) == 0)
		{
			result |= 1<<i;
		}
	}
	return result;
}
